package com.dmall.opening.up.records.dao.mysql.mybatis.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.dmall.opening.up.records.dao.mysql.mybatis.handler.Json.fromJson;
import static com.dmall.opening.up.records.dao.mysql.mybatis.handler.Json.toJson;

@MappedTypes(Map.class)
public class JsonMapHandler implements TypeHandler<Map<String, Object>> {

    static TypeReference<Map<String, Object>> JSON_TYPE = new TypeReference<Map<String, Object>>() {

    };

    @Override
    public void setParameter(PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, (parameter == null) ? "{}" : toJson(parameter));
    }

    @Override
    public Map<String, Object> getResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getString(columnName) != null ? fromJson(rs.getBlob(columnName), JSON_TYPE) : new LinkedHashMap<>();
    }

    @Override
    public Map<String, Object> getResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getString(columnIndex) != null ? fromJson(rs.getBlob(columnIndex), JSON_TYPE) : new LinkedHashMap<>();
    }

    @Override
    public Map<String, Object> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getString(columnIndex) != null ? fromJson(cs.getBlob(columnIndex), JSON_TYPE) : new LinkedHashMap<>();
    }
}
